03. Binary Search Practice

Binary Search Practice

Question:

Searches and sorts can be very hard to visualize and understand. If you need, go through the video a few more times until it really sinks in. Here is a supplementary visualization that might help as well!

Python lists have a method called index() , which just does a search and returns the first index with an instance of that value. Next, you're going to write a binary search function that has the same result, but searches faster. Keep in mind the constraint for this exercise—for binary search, elements need to be in increasing order.

Start Quiz:

"""You're going to write a binary search function.
You should use an iterative approach - meaning
using loops.
Your function should take two inputs:
a Python list to search through, and the value
you're searching for.
Assume the list only has distinct elements,
meaning there are no repeated values, and 
elements are in a strictly increasing order.
Return the index of value, or -1 if the value
doesn't exist in the list."""

def binary_search(input_array, value):
    """Your code goes here."""
    return -1

test_list = [1,3,9,11,15,19,29]
test_val1 = 25
test_val2 = 15
print binary_search(test_list, test_val1)
print binary_search(test_list, test_val2)
Solution:

If you feel like you struggled with this material, check out this visualization . (There's a coded solution there too!)